package com.wolfpire.proms.dao.impl;

import java.util.List;

import org.apache.commons.lang3.ArrayUtils;
import org.hibernate.Criteria;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Repository;

import com.wolfpire.proms.dao.ProjectIndexRoleRelationDao;
import com.wolfpire.proms.model.ProjectIndexRoleRelation;
import com.wolfpire.system.common.base.dao.impl.BaseHibernateDao;

@Repository("projectIndexRoleRelationDao")
public class ProjectIndexRoleRelationDaoImpl extends BaseHibernateDao<ProjectIndexRoleRelation, Long> implements ProjectIndexRoleRelationDao {

	@Override
	public void relate(Long projectIndexId, Long[] roleIds) {
		// 先删除
		this.deleteByProjectIndexId(projectIndexId);
		// 后绑定
		if (ArrayUtils.isNotEmpty(roleIds)) {
			for (Long roleId : roleIds) {
				ProjectIndexRoleRelation pir = new ProjectIndexRoleRelation(projectIndexId, roleId);
				this.saveOrUpdate(pir);
			}
		}
	}
	
	public void deleteByProjectIndexId(Long projectIndexId) {
		String executeSql = "DELETE FROM t_project_index_role WHERE project_index_id = ?";
		this.executeSql(executeSql, projectIndexId);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<ProjectIndexRoleRelation> getPiRRelation(Long projectIndexId) {
		Criteria c = createCriteria().add(Restrictions.eq("projectIndexId", projectIndexId));
		return c.list();
	}
}
